<?php
/**
 * Plugin Name: Modern Options Framework
 * Author: Wangtuike (Optimized by Assistant)
 * Author URI: wanhtuike.com
 * Version: 2.1.0
 * Description: An optimized, modern and functional WordPress options framework
 */

if (!defined('ABSPATH')) {
    exit;
}

class Modern_Fields_Framework {
    protected $option_name = 'modern_options';
    protected $page_slug = 'modern-options-framework';
    protected $fields = [];
    protected $metaboxes = [];

    public function __construct() {
        add_action('admin_menu', [$this, 'add_plugin_page']);
        add_action('admin_init', [$this, 'page_init']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('add_meta_boxes', [$this, 'add_meta_boxes']);
        add_action('save_post', [$this, 'save_metabox_data']);
    }

    public function add_plugin_page() {
        add_menu_page(
            'Modern Options Framework',
            'Modern Options',
            'manage_options',
            $this->page_slug,
            [$this, 'create_admin_page'],
            'dashicons-admin-generic',
            110
        );
    }

    public function create_admin_page() {
        $options = get_option($this->option_name);
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            <?php settings_errors(); ?>
            <form method="post" action="options.php">
                <?php
                settings_fields('modern_options_group');
                do_settings_sections($this->page_slug);
                submit_button();
                ?>
            </form>
            <h2>Current Options:</h2>
            <pre><?php print_r($options); ?></pre>
        </div>
        <?php
    }

    public function enqueue_admin_scripts($hook) {
        if ($hook != 'toplevel_page_' . $this->page_slug && !in_array($hook, ['post.php', 'post-new.php'])) {
            return;
        }
        wp_enqueue_media();
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_enqueue_style('modern-options-css', plugins_url('css/modern-options.css', __FILE__));
        wp_enqueue_script('modern-options-js', plugins_url('js/modern-options.js', __FILE__), ['jquery', 'wp-color-picker'], null, true);
    }

    public function page_init() {
        register_setting('modern_options_group', $this->option_name, [$this, 'sanitize']);

        add_settings_section(
            'general_settings_section',
            'General Settings',
            [$this, 'print_section_info'],
            $this->page_slug
        );


        //add_field($id, $title, $type, $options = []) 
        
        $this->add_field('site_logo','Logo','image');
        $this->add_field('site_heading', 'Site Heading', 'text');
        $this->add_field('site_slogo', 'Site Slogon', 'text');
        $this->add_field('phone_mockup', 'Phone Mockup', 'image');
        $this->add_field('default_banner_image', 'Default Banner Image', 'image');

        $this->add_field('contact','','seperator');

        $this->add_field('address', 'Adress', 'text');
        $this->add_field('phone', 'Phone', 'number');
        $this->add_field('email', 'Email', 'email');
        
        $this->add_field('seperator1','','seperator');
        $this->add_field('site_slogo4', 'Site Slogon1', 'text');
        // $this->add_field('text_input', 'Text Input', 'text');
        // $this->add_field('textarea', 'Textarea', 'textarea');
        // $this->add_field('checkbox', 'Checkbox', 'checkbox');
        // $this->add_field('radio', 'Radio Buttons', 'radio', [
        //     'option1' => 'Option 1',
        //     'option2' => 'Option 2',
        //     'option3' => 'Option 3'
        // ]);
        // $this->add_field('select', 'Select Dropdown', 'select', [
        //     'choice1' => 'Choice 1',
        //     'choice2' => 'Choice 2',
        //     'choice3' => 'Choice 3'
        // ]);
        // $this->add_field('multiselect', 'Multi-Select', 'multiselect', [
        //     'multi1' => 'Multi 1',
        //     'multi2' => 'Multi 2',
        //     'multi3' => 'Multi 3',
        //     'multi4' => 'Multi 4'
        // ]);
        // $this->add_field('color', 'Color Picker', 'color');
        // $this->add_field('image', 'Image Upload', 'image');
        // $this->add_field('password', 'Password Field', 'password');
        // $this->add_field('number', 'Number Input', 'number');
        // $this->add_field('url', 'URL Input', 'url');
        // $this->add_field('email', 'Email Input', 'email');
        // $this->add_field('date', 'Date Picker', 'date');
        // $this->add_field('time', 'Time Picker', 'time');
        // $this->add_field('editor', 'WYSIWYG Editor', 'editor');
    }

    public function add_field($id, $title, $type, $options = []) {
        $this->fields[$id] = [
            'title' => $title,
            'type' => $type,
            'options' => $options
        ];

        

        add_settings_field(
            $id,
            $title,
            [$this, 'render_field'],
            $this->page_slug,
            'general_settings_section',
            ['id' => $id, 'type' => $type, 'options' => $options]
        );
    }

    public function render_field($args) {
        $id = $args['id'];
        $type = $args['type'];
        $options = $args['options'];
        $value = $this->get_field_value($id);

        $this->render_field_by_type($id, $type, $value, $options);
    }

    protected function get_field_value($id) {
        $options = get_option($this->option_name);
        return isset($options[$id]) ? $options[$id] : '';
    }

    protected function render_field_by_type($id, $type, $value, $options = []) {
        $name = "{$this->option_name}[$id]";
        
        switch ($type) {
            case 'text':
            case 'password':
            case 'number':
            case 'url':
            case 'email':
            case 'date':
            case 'time':
                echo "<input type='$type' id='$id' name='$name' value='" . esc_attr($value) . "' class='regular-text' />";
                break;
            case 'textarea':
                echo "<textarea id='$id' name='$name' rows='5' cols='50'>" . esc_textarea($value) . "</textarea>";
                break;
            case 'checkbox':
                $checked = checked($value, 1, false);
                echo "<input type='checkbox' id='$id' name='$name' value='1' $checked />";
                break;
            case 'radio':
            case 'select':
                $this->render_options($type, $id, $name, $value, $options);
                break;
            case 'multiselect':
                echo "<select id='$id' name='{$name}[]' multiple='multiple' style='height: 100px;'>";
                foreach ($options as $key => $label) {
                    $selected = in_array($key, (array)$value) ? 'selected="selected"' : '';
                    echo "<option value='" . esc_attr($key) . "' $selected>" . esc_html($label) . "</option>";
                }
                echo "</select>";
                break;
            case 'color':
                echo "<input type='text' id='$id' name='$name' value='" . esc_attr($value) . "' class='color-picker' />";
                break;
            case 'image':
                echo "<input type='text' id='$id' name='$name' value='" . esc_attr($value) . "' class='regular-text image-url' />";
                echo "<input type='button' class='button upload-image-button' value='Upload Image' data-field='$id' />";
                if (!empty($value)) {
                    echo "<br><img src='" . esc_url($value) . "' class='image-preview' style='max-width:300px;' />";
                }
                break;
            case 'editor':
                wp_editor($value, $id, ['textarea_name' => $name, 'textarea_rows' => 10]);
                break;
            case 'seperator' : 
            echo '<hr>';
            echo '<h3>' . $id .  ' </h3>';
            echo '<hr>';
            break;
        }
    }

    protected function render_options($type, $id, $name, $value, $options) {
        if ($type === 'radio') {
            foreach ($options as $key => $label) {
                $checked = checked($value, $key, false);
                echo "<label><input type='radio' name='$name' value='" . esc_attr($key) . "' $checked /> $label</label><br />";
            }
        } elseif ($type === 'select') {
            echo "<select id='$id' name='$name'>";
            foreach ($options as $key => $label) {
                $selected = selected($value, $key, false);
                echo "<option value='" . esc_attr($key) . "' $selected>" . esc_html($label) . "</option>";
            }
            echo "</select>";
        }
    }

    public function sanitize($input) {
        $new_input = [];
        foreach ($input as $key => $value) {
            if (isset($this->fields[$key])) {
                $new_input[$key] = $this->sanitize_field($this->fields[$key]['type'], $value);
            }
        }

        add_settings_error(
            'modern_options_messages',
            'modern_options_message',
            __('Settings Saved', 'modern-options-framework'),
            'updated'
        );
        return $new_input;
    }

    protected function sanitize_field($type, $value) {
        switch ($type) {
            case 'checkbox':
                return isset($value) ? 1 : 0;
            case 'textarea':
            case 'editor':
                return wp_kses_post($value);
            case 'multiselect':
                return array_map('sanitize_key', (array)$value);
            case 'email':
                return sanitize_email($value);
            case 'url':
                return esc_url_raw($value);
            case 'number':
                return intval($value);
            case 'color':
                return sanitize_hex_color($value);
            default:
                return sanitize_text_field($value);
        }
    }

    public function print_section_info() {
        echo 'Enter your settings below:';
    }

    // Metabox methods
    public function add_metabox($id, $title, $post_types, $context = 'advanced', $priority = 'default') {
        $this->metaboxes[$id] = [
            'title' => $title,
            'post_types' => (array) $post_types,
            'context' => $context,
            'priority' => $priority,
            'fields' => []
        ];
    }

    public function add_metabox_field($metabox_id, $id, $title, $type, $options = []) {
        if (isset($this->metaboxes[$metabox_id])) {
            $this->metaboxes[$metabox_id]['fields'][$id] = [
                'title' => $title,
                'type' => $type,
                'options' => $options
            ];
        }
    }

     public function add_meta_boxes() {
        foreach ($this->metaboxes as $id => $metabox) {
            foreach ($metabox['post_types'] as $post_type) {
                add_meta_box(
                    $id,
                    $metabox['title'],
                    [$this, 'render_metabox'],
                    $post_type,
                    $metabox['context'],
                    $metabox['priority'],
                    ['metabox_id' => $id]
                );
            }
        }
    }

    public function render_metabox($post, $metabox) {
        $metabox_id = $metabox['args']['metabox_id'];
        $fields = $this->metaboxes[$metabox_id]['fields'];

        wp_nonce_field('modern_metabox_' . $metabox_id, 'modern_metabox_nonce_' . $metabox_id);

        foreach ($fields as $id => $field) {
            $value = get_post_meta($post->ID, $id, true);
            echo "<p><label for='$id'>{$field['title']}</label><br>";
            $this->render_field_by_type($id, $field['type'], $value, $field['options']);
            echo "</p>";
        }
    }


    //这里保存时候直接保存了字段了 
    public function save_metabox_data($post_id) {
        foreach ($this->metaboxes as $metabox_id => $metabox) {
            if (!isset($_POST['modern_metabox_nonce_' . $metabox_id])) {
                continue;
            }

            if (!wp_verify_nonce($_POST['modern_metabox_nonce_' . $metabox_id], 'modern_metabox_' . $metabox_id)) {
                continue;
            }

            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
                continue;
            }

            if (!current_user_can('edit_post', $post_id)) {
                continue;
            }

            $posted_data = isset($_POST[$this->option_name]) ? $_POST[$this->option_name] : [];

            foreach ($metabox['fields'] as $field_id => $field) {
                if (isset($posted_data[$field_id])) {
                    $value = $this->sanitize_field($field['type'], $posted_data[$field_id]);
                    update_post_meta($post_id, $field_id, $value);
                } else {
                    delete_post_meta($post_id, $field_id);
                }
            }
        }
    }
}

// Initialize the framework
function initialize_modern_fields_framework() {
    $framework = new Modern_Fields_Framework();

    // Example usage of metaboxes
    // $id, $title, $post_types, $context = 'advanced', $priority = 'default'
    $framework->add_metabox('custom_fields', 'Custom Fields', ['post', 'page']);
    $framework->add_metabox('portfolio_fields', 'Portfolio Fields', ['portfolio']);

    //add_metabox_field($metabox_id, $id, $title, $type, $options = [])

    $framework->add_metabox_field('portfolio_fields', 'client', 'Client name', 'text');
    $framework->add_metabox_field('portfolio_fields', 'industry', __('Industry'), 'text');
    $framework->add_metabox_field('portfolio_fields', 'services', __('服务种类'), 'text');
    $framework->add_metabox_field('portfolio_fields', 'client_url', __('客户网址'), 'url');
    $framework->add_metabox_field('portfolio_fields', 'project_date', __('项目完成时间'), 'date');
    $framework->add_metabox_field('portfolio_fields', 'inner_page_1', __('Inner Page 1'), 'image');
    $framework->add_metabox_field('portfolio_fields', 'inner_page_2', __('Inner Page 2'), 'image');
    $framework->add_metabox_field('portfolio_fields', 'inner_page_3', __('Inner Page 3'), 'image');
    $framework->add_metabox_field('portfolio_fields', 'inner_page_4', __('Inner Page 4'), 'image');

    

    $framework->add_metabox_field('custom_fields', 'custom_text', 'Custom Text', 'text');

    $framework->add_metabox_field('custom_fields', 'custom_number', 'Custom Number', 'number');
    $framework->add_metabox_field('custom_fields', 'custom_checkbox', 'Custom Checkbox', 'checkbox');
    $framework->add_metabox_field('custom_fields', 'custom_select', 'Custom Select', 'select', [
        'option1' => 'Option 1',
        'option2' => 'Option 2',
        'option3' => 'Option 3'
    ]);

    $framework->add_metabox_field('custom_fields', 'image_upload', 'Image Upload', 'image');

    $framework->add_metabox_field('custom_fields', 'custom_text1', 'Custom Text', 'text');
    $framework->add_metabox_field('custom_fields', 'custom_text2', 'Custom Text', 'text');
}

if (is_admin()) {
    add_action('init', 'initialize_modern_fields_framework');
}